<template>
  <div class="containerFather">
    <div class="container">
      <!-- 第一行 -->
      <div class="Item">
        <div class="gailan">
          <div class="title-area">
            <h2>数据概览</h2>
            <p>数据更新：2048-10-15</p>
          </div>
          <div class="ggg">
            <div ref="firstChartRef" class="chart"></div>
            <div ref="secondChartRef" class="chart"></div>
            <div ref="thirdChartRef" class="chart"></div>
            <div ref="fourthChartRef" class="chart"></div>
            <div ref="fifthChartRef" class="chart"></div>
          </div>
        </div>
        <div class="Info">
          <div class="title-area">
            <h2>我的信息</h2>
          </div>
          <div class="mine">
            <img
              src="/src/assets/images/profile.jpg">
            <div class="detail">
              <div class="welcome">您好，<span class="pp">{{userInfo.nickName}}</span>，今天也是元气满满的一天!</div>
              <div class="shuxing">
                <div class="item1">
                   <div class="item">
                    <img
                      src="/src/assets/images/角色.png"
                      alt="">
                    {{userInfo.remark}}
                  </div>
                  <div class="item">
                    <img
                      src="/src/assets/images/部门.png"
                      alt="">
                    {{userInfo.dept.deptName}}
                  </div>
                </div>
                <div class="item2">
                  <div class="item">
                    <img
                      src="/src/assets/images/邮箱.png"
                      alt="">
                    {{userInfo.email}}
                  </div>
                  <div class="item">
                    <img
                      src="/src/assets/images/手机号.png"
                      alt="">
                    {{userInfo.phonenumber}}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="xiashu">
            <div class="wenzi">下属员工</div>
            <div class="wentop">
              <img v-for="(imgUrl, index) in imageList" :key="index" :src="imgUrl.url">
            </div>
          </div>
        </div>
      </div>
      <!-- 第二行 -->
      <div class="Item">
        <div class="tongji">
          <div class="title-area">
            <h2>数据统计</h2>
          </div>
          <div class="HHH">
            <div class="tabs">
              <div v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === index }"
                @click="switchTab(index)">
                {{ tab }}
              </div>
            </div>

            <!-- 时间范围选择（div 替代 button） -->
            <div class="time-filter">
              <span>{{ dateRange }}</span>
              <div v-for="(time, index) in timeOptions" :key="index" :class="{ active: currentTime === index }"
                @click="switchTime(index)">
                {{ time }}
              </div>
            </div>
          </div>
          <!-- 图表容器 -->
          <div ref="chartRef" class="chartS"></div>
        </div>
        <div class="kuaijie">
          <div class="title-area">
            <h2>快捷方式</h2>
          </div>
          <div class="kuaierA">
            <div class="items">
              <div class="KKK" @click="toTodoList">
                <img src="/src/assets/images/待办事项.png">
              </div>
              <div>待办事项</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toIncomeList">
                <img src="/src/assets/images/一键下单.png">
              </div>
              <div>入账列表</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toOrderManagement">
                <img src="/src/assets/images/订单管理.png">
              </div>
              <div>订单管理</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toRefundManagement">
                <img src="/src/assets/images/退款管理.png">
              </div>
              <div>退款管理</div>
            </div>
          </div>
          <div class="kuaierB">
            <div class="items">
              <div class="KKK" @click="toCheckAppeoval">
                <img src="/src/assets/images/入住申请.png">
              </div>
              <div>入住申请</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toReturnOrderManagement">
                <img src="/src/assets/images/采购退货申请单列表.png">
              </div>
              <div>退住申请</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toLeaveAppeoval">
                <img src="/src/assets/images/请假申请.png">
              </div>
              <div>请假申请</div>
            </div>
            <div class="items">
              <div class="KKK" @click="toReservationList">
                <img src="/src/assets/images/预约登记.png">
              </div>
              <div>预约登记</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 第三行 -->
      <div class="Item">
        <div class="daiban">
          <div class="title-area">
            <h2>待办事项</h2>
          </div>
          <div class="todo-list">
            <div v-for="(item, index) in todoData" :key="index">
              <div class="todo-header">
                <span class="todo-type" :class="`type-${item.type}`">
                  {{ item.typeText }}
                </span>
                <span class="todo-desc">
                  {{ item.code }} {{ item.name }}的{{ item.applyType }}
                </span>
                <button class="approve-btn">假的</button>
                <!-- 上面这个按钮占位用 -->
                <button class="approve-btn1">审批</button>
              </div>
              <div class="todo-info">
                申请人：{{ item.applicant }} 申请时间：{{ item.applyTime }}
              </div>
            </div>
          </div>
        </div>
        <div class="zonglan">
          <div class="title-area">
            <h2>预约总览</h2>
            <p>今日：{{ currentDate }}</p>
          </div>
          <!-- 日期选择栏 -->
          <div class="date-picker">
            <button class="arrow-btn" @click="prevWeek">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"
                class="bi bi-chevron-left">
                <path fill-rule="evenodd"
                  d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z" />
              </svg>
            </button>
            <div class="week-days">
              <div v-for="(day, index) in weekDays" :key="index"
                :class="{ 'current-day': day.isCurrent, 'has-reservation': day.hasReservation }">
                {{ day.text }}
              </div>
            </div>
            <button class="arrow-btn" @click="nextWeek">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"
                class="bi bi-chevron-right">
                <path fill-rule="evenodd"
                  d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z" />
              </svg>
            </button>
          </div>
          <!-- 预约列表 -->
          <div class="reservation-list">
            <div v-for="(reservation, index) in reservations" :key="index" class="reservation-item">
              <span
                :class="['reservation-type', { 'visit': reservation.type === '参观', 'visit-other': reservation.type === '探访' }]">
                {{ reservation.type }}
              </span>
              <span class="reservation-time">{{ reservation.time }}</span>
              <span class="reservation-info">预约人：{{ reservation.name }}</span>
              <span class="reservation-info">手机号：{{ reservation.phone }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 第四行 -->
      <div class="Item">
        <div class="level">
          <div class="title-area">
            <h2>老人等级分布</h2>
            <p>数据更新：2048-10-15</p>
          </div>
          <div ref="pieChartRef" class="chart"></div>
        </div>
        <div class="age">
          <div class="title-area">
            <h2>老人年龄分布</h2>
            <p>数据更新：2048-10-15</p>
          </div>
          <div ref="barChartRef" class="chart"></div>
        </div>
        <div class="server">
          <div class="title-area">
            <h2>养老服务能力</h2>
            <p>数据更新：2048-10-15</p>
          </div>
          <div ref="radarChartRef" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, onBeforeUnmount, getCurrentInstance, watch } from 'vue';
import useUserStore from '@/store/modules/user'
import {getUser} from '@/api/system/user'
import router from '@/router';
import { getCount } from '@/api/workbench/workbench';

// 2. 获取用户存储实例
const userStore = useUserStore()
const userId = userStore.id


// 从全局获取 ECharts 实例
const instance = getCurrentInstance();
const echarts = instance.proxy.$echarts;

// 为每个图表容器分别创建 ref
const firstChartRef = ref(null);
const secondChartRef = ref(null);
const thirdChartRef = ref(null);
const fourthChartRef = ref(null);
const fifthChartRef = ref(null);
const pieChartRef = ref(null);
const barChartRef = ref(null);
const radarChartRef = ref(null);
const chartRef = ref(null); // 主统计图表容器

// 声明变量存储每个图表实例
let firstChart = null;
let secondChart = null;
let thirdChart = null;
let fourthChart = null;
let fifthChart = null;
let pieChart = null;
let barChart = null;
let radarChart = null;
let myChart = null; // 主统计图表实例


// ---------- 1. 基础数据定义 ----------
// 下属头像
const imageList = [
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标1' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标2' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标3' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标4' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标5' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标6' },
  { url: 'https://img.tukuppt.com/png_preview/00/05/28/TGbGRvIZAj.jpg!/fw/780', alt: '图标7' }
];

// 当前日期
const currentDate = ref('2048-10-15');

// 星期数据
const weekDays = ref([
  { text: '日', isCurrent: false, hasReservation: false },
  { text: '15', isCurrent: true, hasReservation: true },
  { text: '16', isCurrent: false, hasReservation: false },
  { text: '17', isCurrent: false, hasReservation: false },
  { text: '18', isCurrent: false, hasReservation: false },
  { text: '19', isCurrent: false, hasReservation: false },
  { text: '20', isCurrent: false, hasReservation: false },
  { text: '21', isCurrent: false, hasReservation: false }
]);

// 预约数据
const reservations = ref([
  { type: '参观', time: '09:00', name: '顾廷烨', phone: '12009890987' },
  { type: '参观', time: '10:00', name: '顾廷烨', phone: '12009890987' },
  { type: '探访', time: '11:00', name: '顾廷烨', phone: '12009890987' }
]);

// 待办事项数据
const todoData = ref([
  {
    type: 'checkin',
    typeText: '入住',
    code: 'SP2048101015000001',
    name: '高启强',
    applyType: '入住申请',
    applicant: '顾廷烨',
    applyTime: '2048-10-10 15:00:00'
  },
  {
    type: 'checkout',
    typeText: '退住',
    code: 'SP2048101109300002',
    name: '陈书婷',
    applyType: '退住申请',
    applicant: '高启强',
    applyTime: '2048-10-11 09:30:00'
  },
  {
    type: 'leave',
    typeText: '请假',
    code: 'SP2048101211150003',
    name: '冯程程',
    applyType: '临时外出',
    applicant: '程程',
    applyTime: '2048-10-12 11:15:00'
  },
  {
    type: 'checkin',
    typeText: '入住',
    code: 'SP2048101216450004',
    name: '孟德海',
    applyType: '入住申请',
    applicant: '孟钰',
    applyTime: '2048-10-12 16:45:00'
  },
  {
    type: 'checkout',
    typeText: '退住',
    code: 'SP2048101109300002',
    name: '陈书婷',
    applyType: '退住申请',
    applicant: '高启强',
    applyTime: '2048-10-11 09:30:00'
  },
  {
    type: 'checkin',
    typeText: '入住',
    code: 'SP2048101015000001',
    name: '高启强',
    applyType: '入住申请',
    applicant: '顾廷烨',
    applyTime: '2048-10-10 15:00:00'
  }
]);

// 选项卡（收益情况、入退情况、服务情况）
const tabs = ref(['收益情况', '入退情况', '服务情况']);
// 当前激活的选项卡索引
const currentTab = ref(0);
// 时间范围选项（今日、本周、本月）
const timeOptions = ref(['今日', '本周', '本月']);
// 当前激活的时间范围索引
const currentTime = ref(0); // 默认“今日”
// 时间范围显示文本
const dateRange = ref('2025-10-25');


// ---------- 2. 按时间维度定义独立图表数据（核心修改） ----------
// 结构说明：timeDimensionData[时间索引][数据类型] = 具体数据
// 时间索引：0=今日，1=本周，2=本月；数据类型：0=收益情况，1=入退情况，2=服务情况
const timeDimensionData = ref([
  // 0. 今日数据（按小时/时段统计）
  [
    // 0.0 今日-收益情况（折线图）
    {
      income: [30, 35, 28, 42, 36, 30, 25, 45, 38, 22, 18, 25], // 收入金额（每30分钟）
      refund: [5, 8, 12, 15, 10, 5, 8, 12, 6, 9, 11, 7], // 退款金额（每30分钟）
      xAxis: ['10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30']
    },
    // 0.1 今日-入退情况（柱状图）
    {
      entry: [12, 8, 15, 10, 7, 13, 9], // 入住人数（每2小时）
      exit: [5, 3, 8, 6, 4, 7, 5], // 退住人数（每2小时）
      xAxis: ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00']
    },
    // 0.2 今日-服务情况（折线图）
    {
      count: [15, 22, 18, 25, 19, 28, 21, 17, 23], // 服务次数（每2小时）
      xAxis: ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '24:00']
    }
  ],
  // 1. 本周数据（按天统计）
  [
    // 1.0 本周-收益情况（折线图）
    {
      income: [180, 220, 195, 250, 230, 280, 210], // 收入金额（每天）
      refund: [30, 45, 35, 50, 40, 55, 38], // 退款金额（每天）
      xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    // 1.1 本周-入退情况（柱状图）
    {
      entry: [55, 62, 58, 65, 70, 68, 60], // 入住人数（每天）
      exit: [35, 40, 38, 42, 45, 43, 39], // 退住人数（每天）
      xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    // 1.2 本周-服务情况（折线图）
    {
      count: [120, 150, 135, 160, 145, 170, 130], // 服务次数（每天）
      xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    }
  ],
  // 2. 本月数据（按周/日期段统计）
  [
    // 2.0 本月-收益情况（折线图）
    {
      income: [850, 920, 880, 950], // 收入金额（每周）
      refund: [180, 210, 195, 220], // 退款金额（每周）
      xAxis: ['第1周', '第2周', '第3周', '第4周']
    },
    // 2.1 本月-入退情况（柱状图）
    {
      entry: [280, 310, 295, 320], // 入住人数（每周）
      exit: [190, 210, 200, 220], // 退住人数（每周）
      xAxis: ['第1周', '第2周', '第3周', '第4周']
    },
    // 2.2 本月-服务情况（折线图）
    {
      count: [650, 720, 680, 750], // 服务次数（每周）
      xAxis: ['第1周', '第2周', '第3周', '第4周']
    }
  ]
]);


// ---------- 3. 基础交互方法 ----------
// 上一周
const prevWeek = () => {
  console.log('切换到上一周');
  // 实际项目中可结合dayjs/moment处理日期逻辑
};

// 下一周
const nextWeek = () => {
  console.log('切换到下一周');
  // 实际项目中可结合dayjs/moment处理日期逻辑
};

// 切换选项卡
const switchTab = (index) => {
  currentTab.value = index;
  renderChart(); // 重新渲染图表
};

// 切换时间范围（更新日期显示+重新渲染图表）
const switchTime = (index) => {
  currentTime.value = index;
  // 更新日期范围显示文本（匹配实际时间维度）
  if (index === 0) dateRange.value = '2025-10-25'; // 今日
  else if (index === 1) dateRange.value = '2025-10-20 ~ 2025-10-26'; // 本周
  else if (index === 2) dateRange.value = '2025-10-01 ~ 2025-10-31'; // 本月
  // 重新渲染图表（使用当前时间维度的对应数据）
  renderChart();
};


// ---------- 4. 图表初始化与渲染（核心修改：动态获取时间维度数据） ----------
// 根据当前时间维度和选项卡，渲染对应图表
const renderChart = () => {
  if (!myChart) return;

  let option = {};
  // 获取当前时间维度的所有数据（0=今日，1=本周，2=本月）
  const currentTimeData = timeDimensionData.value[currentTime.value];
  // 获取当前选项卡对应的具体数据（0=收益，1=入退，2=服务）
  const currentTabData = currentTimeData[currentTab.value];

  // 1. 收益情况-折线图（选项卡0）
  if (currentTab.value === 0) {
    option = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['收入金额', '退款金额'] },
      xAxis: { type: 'category', data: currentTabData.xAxis },
      yAxis: { type: 'value' },
      series: [
        {
          name: '收入金额',
          type: 'line',
          data: currentTabData.income,
          itemStyle: { color: '#4895ef' }
        },
        {
          name: '退款金额',
          type: 'line', 
          data: currentTabData.refund,
          itemStyle: { color: '#4ecb73' }
        }
      ]
    };
  }
  // 2. 入退情况-柱状图（选项卡1）
  else if (currentTab.value === 1) {
    option = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['入住人数', '退住人数'] },
      xAxis: { type: 'category', data: currentTabData.xAxis },
      yAxis: { type: 'value' },
      series: [
        {
          name: '入住人数',
          type: 'bar',
          data: currentTabData.entry,
          itemStyle: { color: '#4895ef' }
        },
        {
          name: '退住人数',
          type: 'bar',
          data: currentTabData.exit,
          itemStyle: { color: '#4ecb73' }
        }
      ]
    };
  }
  // 3. 服务情况-折线图（带面积填充）（选项卡2）
  else if (currentTab.value === 2) {
    option = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['服务次数'] },
      xAxis: { type: 'category', data: currentTabData.xAxis },
      yAxis: { type: 'value' },
      series: [
        {
          name: '服务次数',
          type: 'line',
          data: currentTabData.count,
          areaStyle: { color: 'rgba(106, 167, 223, 0.3)' }, // 面积填充样式（保持原样式）
          itemStyle: { color: '#4895ef' }
        }
      ]
    };
  }

  myChart.setOption(option, true);
};

// 初始化所有图表（概览图表+主统计图表）
const initCharts = () => {
  // 先初始化主统计图表
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    renderChart(); // 初始渲染（默认今日+收益情况）
  }

  // 初始化概览图表1：老人数量（饼图）
  if (firstChartRef.value) {
    firstChart = echarts.init(firstChartRef.value);
    const firstChartData = [{ value: 255, name: '外出中' }, { value: 1048, name: '在院' }];
    const firstTotal = firstChartData.reduce((sum, item) => sum + item.value, 0);
    firstChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { show: false },
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '老人数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${firstTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        name: '老人数量',
        type: 'pie',
        radius: ['70%', '90%'],
        selectedMode: 'single',
        avoidLabelOverlap: false,
        label: { show: false, position: 'center' },
        emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: firstChartData,
        color: ['#e0e0e0', '#5A9FFF']
      }]
    });
  }

  // 初始化概览图表2：床位数量（饼图）
  if (secondChartRef.value) {
    secondChart = echarts.init(secondChartRef.value);
    const secondChartData = [{ value: 255, name: '未使用' }, { value: 1048, name: '使用中' }];
    const secondTotal = secondChartData.reduce((sum, item) => sum + item.value, 0);
    secondChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { show: false },
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '床位数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${secondTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        name: '床位数量',
        type: 'pie',
        radius: ['70%', '90%'],
        selectedMode: 'single',
        avoidLabelOverlap: false,
        label: { show: false, position: 'center' },
        emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: secondChartData,
        color: ['#e0e0e0', '#2BC493']
      }]
    });
  }

  // 初始化概览图表3：服务数量（饼图）
  if (thirdChartRef.value) {
    thirdChart = echarts.init(thirdChartRef.value);
    const thirdChartData = [{ value: 2.0, name: '未完成' }, { value: 5.2, name: '已完成' }];
    const thirdTotal = thirdChartData.reduce((sum, item) => sum + item.value, 0);
    thirdChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { show: false },
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '服务数量W', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${thirdTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        name: '服务单数量',
        type: 'pie',
        radius: ['70%', '90%'],
        selectedMode: 'single',
        avoidLabelOverlap: false,
        label: { show: false, position: 'center' },
        emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: thirdChartData,
        color: ['#e0e0e0', '#7A7AFF']
      }]
    });
  }

  // 初始化概览图表4：员工数量（饼图）
  if (fourthChartRef.value) {
    fourthChart = echarts.init(fourthChartRef.value);
    const fourthChartData = [{ value: 240, name: '未在岗' }, { value: 1048, name: '在岗' }];
    const fourthTotal = fourthChartData.reduce((sum, item) => sum + item.value, 0);
    fourthChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { show: false },
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '员工数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${fourthTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        name: '员工数量',
        type: 'pie',
        radius: ['70%', '90%'],
        selectedMode: 'single',
        avoidLabelOverlap: false,
        label: { show: false, position: 'center' },
        emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: fourthChartData,
        color: ['#e0e0e0', '#C4C440']
      }]
    });
  }

  // 初始化概览图表5：收入金额（饼图）
  if (fifthChartRef.value) {
    fifthChart = echarts.init(fifthChartRef.value);
    const fifthChartData = [{ value: 20, name: '未支付' }, { value: 50.2, name: '已支付' }];
    const fifthTotal = fifthChartData.reduce((sum, item) => sum + item.value, 0);
    fifthChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { show: false },
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '收入金额W', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${fifthTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        name: '收入分布',
        type: 'pie',
        radius: ['70%', '90%'],
        selectedMode: 'single',
        avoidLabelOverlap: false,
        label: { show: false, position: 'center' },
        emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: fifthChartData,
        color: ['#e0e0e0', '#FF4444']
      }]
    });
  }

  // 初始化概览图表6：老人等级分布（饼图）
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value);
    pieChart.setOption({
      title: {
        text: '老人等级分布',
        left: 'left',
        textStyle: { color: '#fff', fontSize: 16 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br/>{c}人 {d}%',
        textStyle: { fontSize: 12 }
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 40,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: { fontSize: 12, color: '#858585' },
        data: ['特级护理等级', '一级护理等级', '二级护理等级', '三级护理等级', '四级护理等级']
      },
      series: [{
        name: '老人等级',
        type: 'pie',
        radius: '55%',
        center: ['35%', '50%'],
        selectedMode: 'single',
        label: { show: false },
        emphasis: { label: { show: true, fontSize: 12, fontWeight: 'normal' } },
        labelLine: { show: true, length: 10, length2: 10 },
        data: [
          { value: 1, name: '特级护理等级' },
          { value: 6, name: '一级护理等级' },
          { value: 3, name: '二级护理等级' },
          { value: 8, name: '三级护理等级' },
          { value: 11, name: '四级护理等级' }
        ],
        color: ['#7B68EE', '#4169E1', '#CD5C5C', '#FFD700', '#90EE90']
      }]
    });
  }

  // 初始化概览图表7：老人年龄分布（柱状图）
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value);
    barChart.setOption({
      title: {
        text: '老人年龄分布',
        left: 'left',
        textStyle: { color: '#fff', fontSize: 16 }
      },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: {
        data: ['男', '女'],
        right: 10,
        top: 0,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: { fontSize: 12, color: '#858585' }
      },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        data: ['60岁以下', '60-70岁', '71-80岁', '81-90岁', '90岁以上'],
        axisLabel: { color: '#858585', fontSize: 10 }
      },
      yAxis: { type: 'value', axisLabel: { color: '#858585', fontSize: 12 } },
      series: [
        {
          name: '男',
          type: 'bar',
          stack: '年龄分布',
          barWidth: 30,
          data: [25, 60, 40, 20, 25],
          itemStyle: { color: '#266CDE' }
        },
        {
          name: '女',
          type: 'bar',
          stack: '年龄分布',
          barWidth: 30,
          data: [45, 18, 10, 3, 15],
          itemStyle: { color: '#4ECB73' }
        }
      ]
    });
  }

  // 初始化概览图表8：服务类型分布（雷达图）
  if (radarChartRef.value) {
    radarChart = echarts.init(radarChartRef.value);
    radarChart.setOption({
      title: {
        left: 'left',
        textStyle: { color: '#000', fontSize: 16, fontWeight: 'bold' }
      },
      subtitle: {
        text: '数据更新：2048-10-15',
        left: 'right',
        top: 20,
        textStyle: { fontSize: 12, color: '#666' }
      },
      tooltip: { trigger: 'item', textStyle: { fontSize: 12 } },
      radar: {
        indicator: [
          { name: '助餐', max: 2500 },
          { name: '口部清洁', max: 2500 },
          { name: '洗头', max: 2500 },
          { name: '复健运动', max: 2500 },
          { name: '助浴', max: 2500 }
        ],
        splitLine: { show: true, lineStyle: { color: '#6FA7DF' } },
        axisLine: { show: true, lineStyle: { color: '#858585' } },
        splitArea: { show: false },
        indicatorName: { textStyle: { color: '#666', fontSize: 12 } }
      },
      series: [{
        name: '服务单数量',
        type: 'radar',
        lineStyle: { color: '#4895ef', width: 1 },
        areaStyle: { color: '#6FA7DF', opacity: 0.3 },
        itemStyle: { color: '#4895ef', borderColor: '#4895ef', borderWidth: 2 },
        data: [{ value: [2000, 2000, 1800, 2200, 1900], name: '服务单数量' }]
      }],
      backgroundColor: '#fff'
    });
  }
};

// 图表自适应窗口大小
const handleResize = () => {
  if (myChart) myChart.resize();
  if (firstChart) firstChart.resize();
  if (secondChart) secondChart.resize();
  if (thirdChart) thirdChart.resize();
  if (fourthChart) fourthChart.resize();
  if (fifthChart) fifthChart.resize();
  if (pieChart) pieChart.resize();
  if (barChart) barChart.resize();
  if (radarChart) radarChart.resize();
};

const userInfo = ref({
  nickname: '',
  phonenumber: '',
  dept: {
    deptName: ''
  },
  email: '',
  remark: ''
})


const toOrderManagement = () => {
  router.push('/orderManagement/orderManagementPage');
}
const toRefundManagement = () => {
  router.push('/orderManagement/refundManagementPage');
}
const toCheckAppeoval = () => {
  router.push('/togetherwork/togetherwork1/checkappeoval');
}
const toReturnOrderManagement = () => {
  router.push('/togetherwork/togetherwork1/dropappeoval');
}
const toLeaveAppeoval = () => {
  router.push('/togetherwork/togetherwork1/leaveappeoval');
}
const toTodoList = () => {
  router.push('/togetherwork/togetherwork1/accraditationrecord');
}
const toIncomeList = () => {
  router.push('/financialManagement/billingManagement/accountEntryList');
}
const toReservationList = () => {
  router.push('/commanage/yuyue/yuyue');
}


// 存储API返回的数据
const countData = ref({
  bedCount: 0,
  elderlyCount: 0,
  serviceCount: 0,
  userCount: 0,
  wealthCount: 0
});

// 更新饼图数据的函数
const updateChartData = () => {
  // 更新第一个饼图：老人数量
  if (firstChart && countData.value.elderlyCount > 0) {
    const elderlyTotal = countData.value.elderlyCount;
    const elderlyInHospital = Math.floor(elderlyTotal * 0.7); // 70%在院
    const elderlyOut = elderlyTotal - elderlyInHospital; // 30%外出
    const firstChartData = [
      { value: elderlyOut, name: '外出中' },
      { value: elderlyInHospital, name: '在院' }
    ];
    const firstTotal = firstChartData.reduce((sum, item) => sum + item.value, 0);
    
    firstChart.setOption({
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '老人数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${firstTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        data: firstChartData
      }]
    });
  }

  // 更新第二个饼图：床位数量
  if (secondChart && countData.value.bedCount > 0) {
    const bedTotal = countData.value.bedCount;
    const bedUsed = Math.floor(bedTotal * 0.8); // 80%使用中
    const bedUnused = bedTotal - bedUsed; // 20%未使用
    const secondChartData = [
      { value: bedUnused, name: '未使用' },
      { value: bedUsed, name: '使用中' }
    ];
    const secondTotal = secondChartData.reduce((sum, item) => sum + item.value, 0);
    
    secondChart.setOption({
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '床位数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${secondTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        data: secondChartData
      }]
    });
  }

  // 更新第三个饼图：服务数量
  if (thirdChart && countData.value.serviceCount > 0) {
    const serviceTotal = countData.value.serviceCount;
    const serviceCompleted = Math.floor(serviceTotal * 0.75); // 75%已完成
    const servicePending = serviceTotal - serviceCompleted; // 25%未完成
    const thirdChartData = [
      { value: servicePending, name: '未完成' },
      { value: serviceCompleted, name: '已完成' }
    ];
    const thirdTotal = thirdChartData.reduce((sum, item) => sum + item.value, 0);
    
    thirdChart.setOption({
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '服务数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${thirdTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        data: thirdChartData
      }]
    });
  }

  // 更新第四个饼图：员工数量
  if (fourthChart && countData.value.userCount > 0) {
    const userTotal = countData.value.userCount;
    const userOnDuty = Math.floor(userTotal * 0.85); // 85%在岗
    const userOffDuty = userTotal - userOnDuty; // 15%未在岗
    const fourthChartData = [
      { value: userOffDuty, name: '未在岗' },
      { value: userOnDuty, name: '在岗' }
    ];
    const fourthTotal = fourthChartData.reduce((sum, item) => sum + item.value, 0);
    
    fourthChart.setOption({
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '员工数量', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${fourthTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        data: fourthChartData
      }]
    });
  }

  // 更新第五个饼图：收入金额（以万为单位）
  if (fifthChart && countData.value.wealthCount > 0) {
    const wealthTotal = countData.value.wealthCount;
    const wealthPaid = Math.floor(wealthTotal * 0.8); // 80%已支付
    const wealthUnpaid = wealthTotal - wealthPaid; // 20%未支付
    const fifthChartData = [
      { value: (wealthUnpaid / 10000).toFixed(1), name: '未支付' },
      { value: (wealthPaid / 10000).toFixed(1), name: '已支付' }
    ];
    const fifthTotal = (wealthTotal / 10000).toFixed(1);
    
    fifthChart.setOption({
      graphic: {
        elements: [
          {
            type: 'text',
            left: 'center',
            top: '36%',
            style: { text: '收入金额W', fontSize: 14, fill: '#888', align: 'center' },
            z: 100
          },
          {
            type: 'text',
            left: 'center',
            top: '50%',
            style: { text: `${fifthTotal}`, fontSize: 24, fontWeight: 'bold', fill: '#333', align: 'center' },
            z: 100
          }
        ]
      },
      series: [{
        data: fifthChartData
      }]
    });
  }
};

// ---------- 5. 生命周期与监听 ----------
onMounted(() => {
  getCount().then(res => {
    console.log(res);
    if (res.code === 200) {
      countData.value = res.data;
      // 数据获取后更新图表
      updateChartData();
    }
  })

  getUser(userId).then(res => {
    if (res.code === 200) {
      userInfo.value = res.data
      console.log(userInfo.value.roles[0].roleName);
    }
  })
  initCharts();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  // 销毁所有图表实例，避免内存泄漏
  if (myChart) myChart.dispose();
  if (firstChart) firstChart.dispose();
  if (secondChart) secondChart.dispose();
  if (thirdChart) thirdChart.dispose();
  if (fourthChart) fourthChart.dispose();
  if (fifthChart) fifthChart.dispose();
  if (pieChart) pieChart.dispose();
  if (barChart) barChart.dispose();
  if (radarChart) radarChart.dispose();
  window.removeEventListener('resize', handleResize);
});

// 监听选项卡变化，重新渲染图表
watch(currentTab, () => {
  renderChart();
});

// 监听时间维度变化（冗余监听，确保切换时间时图表必更新）
watch(currentTime, () => {
  renderChart();
});
</script>


<style scoped>
.chartS {
  width: 900px;
  height: 280px;
  position: absolute;
  top: 80px;
  left: -46px;
}

.containerFather {
  background-color: #F1F2F5;
  padding-top: 20px;
  padding-bottom: 30px;
}

.container {
  width: 1292px;
  padding: 16px 18px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  background-color: white;
  margin-left: 18px;
}

.Item {
  display: flex;
  width: 1256px;
  height: 320px;
  justify-content: space-between;
  margin-bottom: 15px;
}

.Item:nth-child(1) {
  width: 1256px;
  height: 270px;
}

.Item:nth-child(4) {
  width: 1256px;
  height: 310px;
  margin-bottom: 10px;
}


.gailan {
  width: 806px;
  height: 270px;
  background-color: red;
  box-sizing: border-box;
  padding: 10px 20px;
  border: 1px solid #c7c7c7;
  background-color: white;
  border-radius: 4px;
}

.ggg {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
  width: 766px;
  height: 170px;
  box-sizing: border-box;
  padding-top: 20px;
}

.tongji {
  width: 806px;
  height: 320px;
  background-color: white;
  box-sizing: border-box;
  padding: 10px 10px;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
  position: relative;
}

.daiban {
  width: 806px;
  height: 320px;
  background-color: white;
  box-sizing: border-box;
  padding: 10px 10px;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

.Info {
  width: 430px;
  height: 270px;
  background-color: white;
  box-sizing: border-box;
  padding: 10px 10px;
  display: flex;
  flex-direction: column;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

.kuaijie {
  width: 430px;
  height: 320px;
  background-color: white;
  box-sizing: border-box;
  padding: 10px 10px;
  display: flex;
  flex-direction: column;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

.zonglan {
  background-color: white;
  width: 430px;
  height: 320px;
  box-sizing: border-box;
  padding: 10px 10px;
  display: flex;
  flex-direction: column;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}


/* 饼图样式 */
.level,
.age,
.server {
  width: 394px;
  height: 310px;
  background-color: white;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

.server {
  width: 430px;
  height: 310px;
}

.title-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  margin-top: 10px;
}

.title-area h2 {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
}

.title-area p {
  font-size: 14px;
  color: #666666;
  margin: 0;
}

.chart {
  width: 100%;
  height: calc(100% - 30px);
}

.mine {
  display: flex;
  margin-top: 10px;
  box-sizing: border-box;
}

.mine img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.item1,
.item2 {
  display: flex;
  justify-content: space-between;
  color: #666666;
  height: 28px;
}

.item1>.item{
  width: 50%;
}
.item2>.item{ 
  width: 50%;
}

.item2 {
  margin-top: 10px;
}

.item1 img {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  vertical-align: middle;
  border-radius: 4px;
}

.item2 img {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  vertical-align: middle;
  border-radius: 4px;
}

.wentop {
  margin-top: 12px;
  width: 386px;
  display: flex;
  justify-content: space-around;
}

.wentop img {
  width: 46px;
  height: 46px;
  border-radius: 50%;
}

.detail {
  margin-left: 20px;
  margin-top: 4px;

}

.xiashu {
  margin-top: 16px;
  font-size: 14px;
  color: #666666;
}

.welcome {
  font-size: 14px;
}

.shuxing {
  font-size: 14px;
  margin-top: 10px;
}

.kuaierA,
.kuaierB {
  width: 410px;
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  padding: 0 10px;
  color: #666666;
  font-size: 14px;
}

.items {
  display: flex;
  flex-direction: column;
  align-items: center;
}


.KKK {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 15px;
  background-color: #dce9fe;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.5s ease;
}

.KKK:hover {
  background-color: rgb(161, 186, 217);
}

.items img {
  width: 32px;
  height: 32px;
}

.tabs {
  display: flex;
  gap: 16px;
  /* 选项卡之间的间距 */
}


.tabs>div {
  cursor: pointer;
  /* 鼠标悬浮时显示手型，提示可点击 */
  position: relative;
  /* 为伪类 ::after 做定位基准 */
  font-size: 14px;
  color: #666666;
}

.tabs>div.active {
  color: #4895ef;
  /* 文字变蓝色 */
}

/* 激活态：蓝色下划线 */
.tabs>div.active::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 1px;
  width: 100%;
  height: 2px;
  color: #4895ef;
  background-color: #4895ef;
  /* 蓝色下划线 */
}

/* 时间范围选择样式 */
.time-filter {
  display: flex;
  align-items: center;
  gap: 12px;
  /* 时间选项之间的间距 */
  margin-bottom: 16px;
}

.time-filter>div {
  cursor: pointer;
  position: relative;
  font-size: 14px;
  color: #666666;
}

.time-filter>div.active {
  color: #4895ef;
}

.time-filter span {
  color: #666;
  font-size: 14px;
}

.chart {
  margin-bottom: 16px;
}

.HHH {
  display: flex;
  justify-content: space-between;
  margin-top: 6px;
  padding: 0 10px;
}

.todo-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  row-gap: 8px;
  column-gap: 24px;
  margin-top: 20px;
}

.todo-item {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background-color: #fff;
  transition: all 0.2s ease;
}

.todo-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #e6f7ff;
}

.todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  position: relative;
}

.todo-type {
  display: inline-block;
  padding: 2px 8px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

/* 动态样式类 */
.type-checkin {
  background-color: #66b1ff;
  color: #266FE8;
}

.type-checkout {
  background-color: #ffe6a8;
  color: #fca518;
}

.type-leave {
  background-color: #ff9d9d;
  color: #fd5858;
}

.todo-desc {
  font-size: 14px;
  font-weight: bold;
  margin-right: 12px;
}

.todo-code {
  font-size: 12px;
  color: #999;
}

.todo-content {
  margin-bottom: 12px;
}

.todo-content p {
  margin: 6px 0;
  font-size: 14px;
}

.todo-info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.approve-btn {
  background-color: white;
  color: #fff;
  width: 54px;
  height: 30px;
  border-radius: 2px;
  border: none;
}

.approve-btn1 {
  position: absolute;
  top: 20px;
  right: 0;
  width: 54px;
  height: 30px;
  border-radius: 2px;
  border: none;
  background-color: #0052D9;
  color: #fff;
}

.approve-btn1:hover {
  background-color: #01327c;
}

.date-info .today {
  color: #42b983;
  margin-right: 8px;
}

.date-picker {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 12px;
}

.arrow-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  margin: 0 8px;
  color: #42b983;
}

.week-days {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.week-days div {
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  cursor: pointer;
}

.current-day {
  background-color: #42b983;
  color: #fff;
}

.has-reservation {
  position: relative;
}

.has-reservation::before {
  content: '';
  position: absolute;
  bottom: 2px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #42b983;
}

.reservation-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reservation-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #F3F8F9;
  border-radius: 6px;
}

.reservation-type {
  padding: 4px 8px;
  border-radius: 10px;
  color: #fff;
  margin-right: 12px;
  font-size: 12px;
}

.visit {
  background-color: #42b983;
}

.visit-other {
  background-color: #ff6b6b;
}

.reservation-time {
  font-weight: bold;
  margin-right: 12px;
  font-size: 14px;
}

.reservation-info {
  margin-right: 12px;
  color: #666;
  font-size: 14px;
}
.pp{
  color: #0052D9;
}

</style>